<template>
    <div>
      <n-grid x-gap="5">
        <n-gi :span="6">
          <n-card>
              <n-form-item>
                <n-select
                    style="width: 100%"
                    :options="parentTag"
                    label-field="categoryName"
                    value-field="id"
                    default-value="01"
                    @update:value="parentTagChange"
                    v-model:value="topParentId">
                </n-select>
                  <n-button type="primary" @click="tagCategoryForm.parentId='';tagCategoryAddShow = true;">
                      新增
                  </n-button>
              </n-form-item>
            <n-dropdown
              trigger="manual"
              placement="bottom-start"
              :show="showDropdown"
              :options="dropDownOptions"
              :x="x"
              :y="y"
              @select="handleSelect"
              @clickoutside="handleClickoutside"
            />
            <n-scrollbar :style="{ height: clientHeight - (layoutHeaderHeight  + tabsHeight + 136) + 'px'}" >
              <n-tree
                  style="margin-top: 5px;"
                  block-line
                  expand-on-click
                  :data="tagTree"
                  label-field="categoryName"
                  key-field="id"
                  children-field="children"
                  :node-props="nodeProps"
              />
            </n-scrollbar>
          </n-card>
        </n-gi>
        <n-gi :span="18">
          <n-card>
            <n-space style="margin-bottom: 10px">
              <n-input v-model:value="tagAttrQueryForm.queryZh" placeholder="标签" style="width: 300px">
              </n-input>
              <n-button type="primary" :on-click="loadAttr">查询</n-button>
            </n-space>
          </n-card>
          <n-card style="margin-top: 5px">
            <n-space justify="end">
              <n-button type="primary" style="margin-bottom: 10px;" @click="tagAddShow = true;">
                新增标签
              </n-button>
              <n-button type="primary" style="margin-bottom: 10px;" @click="batchTagAddShow = true;">
                批量导入
              </n-button>
            </n-space>
            <n-data-table
                :columns="columns"
                :data="tagAttrList"
                :loading="tableLoading"
                :style="{ height: `${clientHeight - (layoutHeaderHeight  + tabsHeight + 225)}px` }"
                flex-height
            >
            </n-data-table>
            <n-space justify="end" style="margin-top: 10px">
              <n-pagination
                  :display-order="['quick-jumper', 'pages', 'size-picker']"
                  :item-count="tableTotal"
                  :page-size="paginationReactive.pageSize"
                  :page-sizes="paginationReactive.pageSizes"
                  show-quick-jumper
                  show-size-picker
                  :on-update:page-size="onPageSizeChange"
                  :on-update:page="onPageChange"
              />
            </n-space>
          </n-card>
        </n-gi>
      </n-grid>
      <n-modal
        v-model:show="tagAddShow"
        class="custom-card"
        preset="card"
        :style="{ width: 600+'px' }"
        title="新增标签"
        size="huge"
        :bordered="false"
        >
        <n-form :rules="rules" ref="formRef" :model="tagAttributeForm">
            <n-form-item label="类目" path="categoryId">
                <n-tree-select
                    :options="tagTree"
                    label-field="categoryName"
                    key-field="id"
                    children-field="children"
                    v-model:value="tagAttributeForm.categoryId"
                    :show-path="true"
                >
                </n-tree-select>
            </n-form-item>
            <n-form-item label="标签 - 中文" path="zh">
                <n-input
                    v-model:value="tagAttributeForm.zh"></n-input>
            </n-form-item>
            <n-form-item label="标签 - 英文" path="en">
                <n-input
                    v-model:value="tagAttributeForm.en"></n-input>
            </n-form-item>
        </n-form>
        <template #footer>
            <n-space justify="end">
                <n-button type="primary" @click="addAttribute" :loading="addAttributeLoading">确定</n-button>
            </n-space>
        </template>
    </n-modal>


      <n-modal
          v-model:show="batchTagAddShow"
          class="custom-card"
          preset="card"
          :style="{ width: 600+'px' }"
          title="批量导入"
          size="huge"
          :bordered="false"
      >
        <n-form :rules="rules" ref="formRef" :model="tagAttributeBatchForm">
          <n-form-item label="类目" path="categoryId">
            <n-tree-select
                :options="tagTree"
                label-field="categoryName"
                key-field="id"
                children-field="children"
                v-model:value="tagAttributeBatchForm.categoryId"
                :show-path="true"
            >
            </n-tree-select>
          </n-form-item>
          <n-form-item label="导入内容" path="zh">
            <n-input
                type="textarea"
                style="height: 300px;"
                v-model:value="tagAttributeBatchForm.batchContent"></n-input>
          </n-form-item>
        </n-form>
        <template #footer>
          <n-space justify="end">
            <n-button type="primary" @click="batchAddAttribute" :loading="addAttributeLoading">确定</n-button>
          </n-space>
        </template>
      </n-modal>

    <n-modal
        v-model:show="tagCategoryAddShow"
        class="custom-card"
        preset="card"
        :style="{ width: 600+'px' }"
        title="新增类目"
        size="huge"
        :bordered="false"
    >
        <n-form :rules="rules" ref="addCategoryformRef" :model="tagCategoryForm">
            <n-form-item label="父目录" path="parentId">
                <n-tree-select
                    :options="tagTree"
                    label-field="categoryName"
                    key-field="id"
                    children-field="children"
                    v-model:value="tagCategoryForm.parentId"
                    :show-path="true"
                    clearable
                >
                </n-tree-select>
            </n-form-item>
            <n-form-item label="类目名" path="categoryName">
                <n-input
                    v-model:value="tagCategoryForm.categoryName">
                </n-input>
            </n-form-item>
            <n-form-item label="浏览类型" path="categoryRange">
                <n-select
                    v-model:value="tagCategoryForm.categoryRange"
                    default-value="0"
                    :options="categoryRangeOption"
                >
                </n-select>

            </n-form-item>
        </n-form>
        <template #footer>
            <n-space justify="end">
                <n-button type="primary" @click="addCategory" :loading="addAttributeLoading">确定</n-button>
            </n-space>
        </template>
    </n-modal>

    </div>
</template>

<script lang="ts" setup>
import {h, onMounted, reactive, ref} from 'vue'
import {NButton,TreeOption} from "naive-ui"
import {tagCategoryController} from '@/api/controller/tagcategory/tagCategoryController'
const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());
import {storeToRefs} from "pinia"
import {useSystemStore} from "@/store/modules/useSystemStore"
const formRef = ref(null)
const addCategoryformRef = ref(null)
const tagAddShow = ref(false)
const batchTagAddShow = ref(false)
const parentTag = ref([])
const tagTree = ref([])
const tagAttrList = ref([])
const tableLoading = ref(false)
const addAttributeLoading = ref(false)
const x = ref(0)
const y = ref(0)
const showDropdown = ref(false)
const tagCategoryAddShow = ref(false)
const topParentId = ref('01')
const selectCategory  = ref('')
const tagAttrQueryForm = reactive({
    queryEn: '',
    queryZh: '',
    categoryId: ''
})
const tagAttributeForm = reactive({
    categoryId: '',
    name: '',
    value: '',
    en:'',
    zh:''
})

const tagAttributeBatchForm = reactive({
  categoryId: '',
  batchContent: ''
})

const tagCategoryForm = reactive({
    id:'',
    categoryName: '',
    categoryCode: '',
    categoryRange:'',
    categoryVisible: '',
    parentId: ''

})

const dropDownOptions = [
    {
        label: '新增目录',
        key: 'addTagCategory'
    },{
        label: '删除目录',
        key: 'deleteCategory'
    }
]

const categoryRangeOption = [
    {
        label: '全部',
        value: 'all'
    },{
        label: 'NSFW',
        value: 'adult'
    }
]


const rules = {
    categoryId: {
        required: true,
        message: '请选择类目',
        trigger: 'submit',
    },
    en: {
        required: true,
        message: '请输入标签 - 英文',
        trigger: 'submit',
    },
    zh: {
        required: true,
        message: '请输入标签 - 中文',
        trigger: 'submit',
    },
    categoryName: {
        required: true,
        message: '请输入名称',
        trigger: 'submit',
    },
    categoryRange: {
        required: true,
        message: '请选择范围',
        trigger: 'submit',
    }
}


const nodeProps = ({ option }: { option: TreeOption }) => {
  return {
    onClick () {
      if (!option.children && !option.disabled) {
          tagAttrQueryForm.categoryId = option.id
          tagAttributeForm.categoryId = option.id
          tagAttributeBatchForm.categoryId = option.id
          loadAttr()
      }
    },
    onContextmenu (e: MouseEvent): void {
          selectCategory.value = option.id
          showDropdown.value = true
          x.value = e.clientX
          y.value = e.clientY
          e.preventDefault()
      }
  }
}

const tableTotal = ref(0)
const paginationReactive = reactive({
    page: 1,
    pageSize: 15,
    pageSizes: [15,30]
})

const onPageSizeChange = (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    loadAttr()
}

const onPageChange = (page: number) => {
    paginationReactive.page = page
    loadAttr()
}

onMounted(()=>{
    // getList()
  getParentCategory()
  loadAttr()
})

const loadAttr =()=>{
    // const data =
    tagCategoryController.getTagAttributeList(tagAttrQueryForm,{
        page: paginationReactive.page,
        pageSize: paginationReactive.pageSize
    }).then((res)=>{
        if(res.code == 200){
            tagAttrList.value = res.data.list
            tableTotal.value = res.data.count
        }
    })
}

const getParentCategory = async() =>{
    tagCategoryController.listParentCategory().then((res)=>{
        if(res.code === 200){
          console.log(res.data)
          parentTag.value = res.data
          if(parentTag.value.length > 0){
            getCategoryTree(parentTag.value[0]?.id)
          }
        }
    })
}

const getCategoryTree = (parentId:string) =>{
    tagCategoryController.listTagCategoryTree(parentId).then((res)=>{
        if(res.code === 200){
          tagTree.value = res.data
        }
    })
}

const parentTagChange = (value:any,option:any) =>{
    getCategoryTree(option.id)
}

const columns = [
   {
        title: '名称',
        key: 'zh'
    },{
        title: '英文',
        key: 'en'
    },{
        title: '操作',
        key: 'action',
        render (row:any) {
            return h(
                NButton,
                {
                    size: 'small',
                    type: 'error',
                    onClick: () => deleteRow(row)
                },
                { default: () => '删除' }
            )
        }
    }
]


const batchAddAttribute = () =>{
  tagCategoryController.batchAddTagAttribute(tagAttributeBatchForm).then((res)=>{
    if(res.code === 200){
      batchTagAddShow.value = false
      loadAttr()
      tagAttributeBatchForm.batchContent = ''
    }
  })
}

const addAttribute = () =>{
    formRef.value?.validate((errors) => {
        if (!errors) {
            addAttributeLoading.value = true
            tagCategoryController.addTagAttribute(tagAttributeForm).then((res)=>{
                addAttributeLoading.value = false
                if(res.code === 200){
                    tagAddShow.value = false
                    loadAttr()
                    tagAttributeForm.en =''
                    tagAttributeForm.zh =''
                }
            })
        }
    })
}

const addCategory = () =>{
  if(tagCategoryForm.parentId==''){
    tagCategoryForm.parentId = topParentId.value
  }
  addCategoryformRef.value?.validate((errors) => {
      if (!errors) {
          addAttributeLoading.value = true
          tagCategoryController.addTagCategory(tagCategoryForm).then((res)=>{
              addAttributeLoading.value = false
              if(res.code === 200){
                tagCategoryAddShow.value = false
                getCategoryTree(topParentId.value)
                tagCategoryForm.categoryName=''
                tagCategoryForm.categoryRange=''
              }
          })
      }
  })
}


const deleteRow = (row:any) =>{
    window.$dialog.error({
        title: "温馨提醒",
        content: "删除操作不可逆，是否继续？",
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: () => {
            tagCategoryController.deleteTagAttribute(row.id).then((res: any) => {
                if(res.code == 200){
                    window.$message.success('删除成功')
                    loadAttr()
                }
            })
        }
    })
}

const deleteCategory = () =>{
    window.$dialog.error({
        title: "温馨提醒",
        content: "删除操作不可逆，是否继续？",
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: () => {
            tagCategoryController.deleteTagCategory(selectCategory.value).then((res: any) => {
                if(res.code == 200){
                    window.$message.success('删除成功')
                    getParentCategory()
                }
            })
        }
    })
}

const handleSelect = (key) => {
    if(key=='addTagCategory'){
      tagCategoryAddShow.value = true
      tagCategoryForm.parentId = selectCategory.value
      showDropdown.value = false
    }else {
        deleteCategory()
    }
}

const handleClickoutside= () => {
    showDropdown.value = false
}

</script>

